IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[FUBGetDateFromParts]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
	DROP FUNCTION [dbo].[FUBGetDateFromParts]
END
GO

-- select dbo.FUBGetDateFromParts (2000, 12, 2)
-- select dbo.FUBGetDateFromParts (2000, 12, NULL)
-- select dbo.FUBGetDateFromParts (2000, NULL, NULL)

CREATE FUNCTION FUBGetDateFromParts (@pYear NUMERIC (4,0), @pMonth NUMERIC (2, 0), @pDay NUMERIC (2, 0))
RETURNS DATETIME
AS
BEGIN

	DECLARE @strDate AS VARCHAR (8)
	DECLARE @result DATETIME
	

	IF (@pYear IS NULL OR @pMonth IS NULL OR @pYear < 1000 OR @pYear > 9999 OR @pDay < 1 OR @pDay > 31) 
	BEGIN
		SET @result = NULL;
	END
	ELSE
	BEGIN
	
		SET @strDate = CONVERT (VARCHAR, @pYear)
		
		IF @pMonth IS NULL
			SET @strDate = @strDate + '01'
		ELSE
		BEGIN
			IF @pMonth < 10
				SET @strDate = @strDate + '0'
		
			SET @strDate = @strDate + CONVERT (VARCHAR, @pMonth)
		END
		
		IF @pDay IS NULL
			SET @strDate = @strDate + '01'
		ELSE
		BEGIN
			IF @pDay < 10
				SET @strDate = @strDate + '0'
			
			SET @strDate = @strDate + CONVERT (VARCHAR, @pDay)
		END
		

		SET @result = CONVERT (DATETIME, @strDate, 112)
		
	END
	
	
	RETURN @result
	
END